package com.linhh.mall.center.common.util;

import cn.hutool.core.util.IdUtil;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;

/**
 * @Author linhh
 * @Date 2023 02 21 01 59
 **/
public class FileUtil {

    /**
     * MultipartFile文件转File文件
     * @param multipartFile
     * @param directory
     * @return
     */
    public static File toFile(MultipartFile multipartFile, String directory){
        String fileName = multipartFile.getOriginalFilename();
        String prefix = "."+getExtensionName(fileName);
        File file = null;
        File diectory = new File(directory);
        try{
            file = File.createTempFile(IdUtil.simpleUUID(),prefix,diectory);
            multipartFile.transferTo(file);

        }catch (IOException e){
            e.printStackTrace();
        }
        return file;
    }

    /**
     * 获取文件扩展名，不带 '.'
     * @param fileName
     * @return
     */
    public static String getExtensionName(String fileName){
        if((fileName != null)&&(fileName.length()>0)){
            int dot = fileName.lastIndexOf('.');
            if((dot >-1)&&(dot<(fileName.length()-1))){
                return fileName.substring(dot + 1);
            }
        }
        return fileName;
    }
}
